<template>
	<view>
		<!-- <view class="login" @click="regist">
			登录
		</view> -->

		<!-- 搜索栏 -->
		<!-- <view class="search-view">
			<uni-search-bar class="search-bar" bgColor="#F1F1F1" radius="35" @confirm="searchConfirm" @input="searchInput" @cancel="searchCancel" />
			<view class="search-bar-mask" @click="search"></view>
		</view> -->
		<!-- 轮播图 -->
		<swiper v-if="bannerDataList && bannerDataList.length" class="images-view" :indicator-dots="true" indicator-active-color="#FFFFFF" :autoplay="true" :interval="3000" :duration="300">
			<swiper-item v-for="(item, index) in bannerDataList" :key="index">
				<!-- <video v-if="isMp4(item)" class="swiper-item main-image" :src="item" alt="商品图片" controls vslide-gesture="true" vslide-gesture-in-fullscreen="true" show-mute-btn="true" muted="true" show-fullscreen-btn="false" enable-play-gesture="true"></video> -->
				<!-- <image class="swiper-item" :src="item.pic" alt="商品图片" mode="scaleToFill" @click="banner(index)"></image> -->
				<image class="swiper-item" :src="item.pic" alt="商品图片" mode="scaleToFill" @click="banner(index)"></image>
			</swiper-item>
		</swiper>

		<!-- <scroll-view class="JSSegmentedControl" scroll-x="trues" @scroll="scroll">
			<view class="JSSegmentedControlItem" v-for="(item, index) in segmentedControlTitles" :key="index" @click="segmentControlDidSelected(index)">
				<view :class="[segmentedControlSelectedIndex == index ? 'JSSegmentedControlItemTitle-selected' : 'JSSegmentedControlItemTitle-normal']">{{item}}</view>
				<view :class="[segmentedControlSelectedIndex == index ? 'JSSegmentedControlItemLine lineSelected' : 'JSSegmentedControlItemLine lineNormal']"></view>
			</view>
		</scroll-view> -->

		<!-- 商品列表 -->
		<view v-if="!dataListIsEmpty" class="dataListView">
			<view class="item" v-for="(item, index) in dataList" :key="index"  @click="detail(index)">
				<view class="item-image-view">
					<image class="item-image" :src="item.pic" mode="aspectFill"></image>
					<view class="item-intro">
						<view class="item-intro-text util-font-regular">{{item.name}}</view>
					</view>
					<view v-if="item.time" class="">
						<view v-if="item.time == '已结束'" class="item-time" style="background: rgba(140,140,140,0.8); width: auto;">{{item.time}}</view>
						<view v-else class="item-time">{{item.time}}</view>
					</view>
				</view>
				<view class="item-mer-view">
					<view class="item-mer-name util-font-medium">{{item.merMerchant.name}}</view>
					<view class="item-mer-distance util-font-regular">{{item.distance?item.distance:''}}</view>
				</view>
				<view class="price-view util-font-regular">
					<view class="price-icon">￥</view>
					<view class="price-text">{{item.price/100.0}}</view>
					<!-- <view class="price-red-packet">使用红包再减{{(item.price/100.0)/10.0}}元</view> -->
					<view class="price-original util-font-regular">门店价￥{{item.originalPrice/100.0}}</view>
					<view v-if="userInfo && userInfo.type == 1" class="price-brokerage">返佣{{item.merProductCommission.littleExpert/100.0}}元</view>
					<view v-else-if="userInfo && userInfo.type == 2" class="price-brokerage">返佣{{item.merProductCommission.bigExpert/100.0}}元</view>
				</view>
			</view>
			<uni-load-more v-if="currentPage == totalPage" :status="'noMore'" @clickLoadMore="loadMore"></uni-load-more>
			<uni-load-more v-else :status="'loading'" @clickLoadMore="loadMore"></uni-load-more>
		</view>
		<view v-else class="empty-view">
			<image class="empty-image" src="../../static/noData.png" mode="aspectFit"></image>
			<view class="empty-title util-font-medium">暂无数据</view>
		</view>		
	</view>
</template>

<script>
	import uniIcons from "@/components/uni-icons/uni-icons.vue"
	import uniSearchBar from '@/components/uni-search-bar/uni-search-bar.vue'
	import uniLoadMore from "@/components/uni-load-more/uni-load-more.vue"

	export default {
		components: {
			uniIcons,
			uniSearchBar,
			uniLoadMore
		},
		data() {
			return {
				inviteUserId: null,
				shareUserId: null,
				verifyCode: null,
				
				segmentedControlTitles: ["爆品推荐", "待支付", "待收货", "退款/售后"],
				segmentedControlSelectedIndex: -1,

				userInfo: null,
				bannerDataList: [],
				dataList: [],
			 	dataListIsEmpty: false,
				currentPage: 1,
				totalPage: 1,
				
				timer: null,
				
				count: 0,
				
			}
		},
		onLoad(options) {
			
			uni.showShareMenu({
				
			})
			
			uni.$off("loginSuccess")
			uni.$off("getPhoneNumberSuccess")
			uni.$off("getLocationSuccess")
			uni.$off("getLocationFailure")
			
			// 获取可能存在的 IUID 或 PUID
			if (options.scene) {
				this.inviteUserId = this.$util.JSDecode(decodeURIComponent(options.scene)).IUID
				this.pullUserId = this.$util.JSDecode(decodeURIComponent(options.scene)).PUID
				this.verifyCode = this.$util.JSDecode(decodeURIComponent(options.scene)).CODE
			}
			if (options.IUID) {
				this.inviteUserId = options.IUID
			}
			if (options.PUID) {
				this.pullUserId = options.PUID
			}
			// 如果 PUID 存在,则暂存
			if (this.pullUserId) {
				uni.setStorageSync('pullUserId', this.pullUserId)
			}
			
			console.log(this.inviteUserId + "********" + this.pullUserId)
			
			var that = this
			uni.$on('loginSuccess', function(){
				that.userInfo = uni.getStorageSync('userInfo')
				
				if (that.verifyCode && that.verifyCode.length == 9){
					that.sendRequest({
						url: 'app/ordOrders/verifyUser',
						method: 'POST',
						header: that.$urlRequest.getHeader('token'),
						data: {
							code: that.verifyCode,
							userId: uni.getStorageSync('userInfo').id
						},
						success: function(res){
							if (res.data.code == 0){
								uni.navigateTo({
									url: '../merchantTools/takeOrderSuccess'
								})
							}else{
								uni.showModal({
									content: ''+res.data.msg,
									showCancel: false
								});
							}
						}
					})
				}
			})
			uni.$on('getPhoneNumberSuccess', function(){
				that.userInfo = uni.getStorageSync('userInfo')
				if (that.inviteUserId && (that.userInfo.superiorId == null)) {
					that.inviteTalent(that.userInfo.id, that.inviteUserId)
				}
			})
			uni.$on('getLocationSuccess', function(){
				that.getDistanceList()
			})
			uni.$on('getLocationFailure', function(){
				
			})
			if (this.inviteUserId || this.pullUserId) {
				if (this.inviteUserId) {
					this.reg("getPhoneNumber")
				}else{
					this.reg()
				}
			}else{
				this.login()
			}
			
			this.loadBannerData()
			this.loadData()
			this.$urlRequest.getLocation()
			// this.loadH5Data()
			// this.$wechat.isWechat()	
			
			// this.wxlogin()
		},
		methods: {
			wxlogin: function(){
				var that = this
				uni.login({
					success(res) {
						console.log('*********' + JSON.stringify(res))
						console.log('************' + res.code)
						that.count++
						setTimeout(function(){
							if (that.count <= 10) {
								that.wxlogin()
							}
						},1000)
					}
				})
			},
			inviteTalent: function(userId, shareUserId){
				if (userId == shareUserId) {
					return
				}
				var that = this
				that.sendRequest({
					url: 'app/appUser/inviteTalent',
					header: that.$urlRequest.getHeader('token', 'json'),
					method: 'POST',
					data: {
						userId: userId,
						shareUserId: shareUserId
					},
					success: function(res) {
						if (res.data.code == 0) {
							uni.showModal({
								content: '您已成为分享达人',
								showCancel: false
							});
						}
					}
				})
			},
			loadBannerData: function(){
				var that = this
				that.sendRequest({
					url: 'app/appBanner/page',
					method: 'POST',
					header: that.$urlRequest.getHeader('void'),
					success: function(res){
						
						that.bannerDataList = res.data.records
					}
				})
			},
			loadData: function() {
				
				var that = this
				var data = {
					limit: 10,
					page: that.currentPage
				}
				this.sendRequest({
					url: 'app/merProduct/proPage',
					method: 'POST',
					header: that.$urlRequest.getHeader('void', 'json'),
					data: data,
					success: function(res){
						
						// 总页数
						that.totalPage = res.data.pages
		
						// 判断是否为第一页数据，如果是，则直接赋值，否则将返回数据添加到数组中
						if (that.currentPage == 1) {
							that.dataList = res.data.records
						}else{
							that.dataList = that.dataList.concat(res.data.records) // arr.concat() 数组连接
						}
						
						// 判断当前页面是否有数据
						if (that.dataList.length == 0) {
							that.dataListIsEmpty = true
						}else{
							that.dataListIsEmpty = false
						}
						
						// 添加定时器
						that.timer = setInterval(function(){
							that.getTimeList()
						}, 1000)
						
						// 添加距离信息
						if (uni.getStorageSync('userLocation')) {
							that.getDistanceList()
						}
					}
				})
			},
			loadH5Data: function(){
				// location.href = 'http://api.wlkjlife.cn/app/wx/mp/wxa9697d11035f69d5/preAuth'
				// var that = this
				// uni.request({
				// 	url: '',
				// 	method:'GET',
				// 	success(res) {
				// 		uni.showModal({
				// 			content: '' + JSON.stringify(res),
				// 			showCancel: false
				// 		});
				// 	}
				// })
			},
			getTimeList: function() {
				
				var that = this
				let newDataList = []
				for (var i = 0; i < this.dataList.length; i++) {
					var item = this.dataList[i]
					
					var finishTime = Date.parse(item.downTime)
					var nowTime = Date.parse(Date())
					var subTime = finishTime - nowTime
					
					if (subTime <= 0) {
						item.time = '已结束'
					}else{
						var day = that.$util.formatNumber(Math.floor(subTime / (1000 * 60 * 60 * 24)))
						var hour = that.$util.formatNumber(Math.floor((subTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)))
						var minute = Math.floor((subTime % (1000 * 60 * 60)) / (1000 * 60))
						var second = Math.floor((subTime % (1000 * 60)) / 1000)
						item.time = day + '日' + that.$util.formatNumber(hour) + '时' + that.$util.formatNumber(minute) + '分' + that.$util.formatNumber(second) + '秒后结束';
					}
					
					newDataList.push(item)
				}
				this.dataList = newDataList
			},
			getDistanceList: function(){
				var userLocation = uni.getStorageSync('userLocation')
				for (var i = 0; i < this.dataList.length; i++) {
					var item = this.dataList[i]
					item.distance = this.getDistance(item.merMerchant.lat, item.merMerchant.lng, userLocation.latitude, userLocation.longitude)
					this.dataList.splice(i,1,item)
				}
			},
			loadMore: function(){
				this.currentPage ++ 
				this.loadData()
			},
			search: function(){
				uni.navigateTo({
					url: 'search'
				})
			},
			banner: function(index){
				var that = this
				var item = this.bannerDataList[index]
				if (item.type == 0) {
					uni.navigateTo({
						url: 'detail?pid=' + item.productId
					})
				}else if (item.type == 1) {
					uni.navigateTo({
						url: '../webview/webview?src=' + item.url
					})
				}
			},
			detail: function(index){
				var that = this
				var item = this.dataList[index]
				
				if (item.time == '已结束') {
					uni.showModal({
						content: '该商品已结束售卖',
						showCancel: false
					});
					return
				}
				
				uni.navigateTo({
					url: 'detail?pid=' + item.id
				})
			},
			searchInput: function(event) {
				console.log("输入内容为：" + event.value)
			},
			searchConfirm: function(event) {
				console.log("确认输入内容为：" + event.value)
			},
			searchCancel: function(event) {
				console.log("取消输入")
			}
		},
		onReachBottom() {
			if (this.currentPage >= this.totalPage) {
				
			}else{
				this.currentPage += 1
				this.loadData()
			}
		},
		onPullDownRefresh() {
			this.loadBannerData()
			this.totalPage = 1
			this.currentPage = 1
			this.dataList = []
			this.loadData()
		},
		
		onShareAppMessage() {
			var that = this
			return {
				title: '省钱有窍门，赚钱有捷径',
				path: '/pages/index/index'
			}
		}
	}
</script>

<style>
	.login {
		width: 300upx;
		height: 88upx;
		color: #333333;
		border: 2upx solid #f1f1f1;
	}

	page {
		background-color: #f5F5F5;
	}

	.search-view {
		width: 690upx;
		height: 70upx;
		overflow: hidden;
		background-color: white;
		padding: 30upx;
		position: relative;
	}

	/* #ifdef MP-WEIXIN */
	.search-view {
		width: 722upx;
		height: 102upx;
		overflow: hidden;
		background-color: white;
		padding: 14upx;
	}

	/* #endif */
	.search-bar {
		width: 690upx;
		height: 70upx;
		padding: 0upx;
	}
	
	.search-bar-mask {
		width: 690rpx;
		height: 70rpx;
		position: absolute;
		padding: 30upx;
		top: 0;
		left: 0;
	}

	.images-view {
		width: 690upx;
		height: 276upx;
		padding: 30upx 30upx 30upx 30upx;
		background-color: white;
	}

	.swiper-item {
		width: 690upx;
		height: 276upx;
		background-color: #F1F1F1;
		/* margin: 1upx; */
		border-radius: 20upx;
	}

	.item {
		margin: 30upx 30upx 0;
		border-radius: 20upx;
		overflow: hidden;
		background-color: #FFFFFF;
	}

	.item-image-view {
		width: 690upx;
		height: 426upx;
		overflow: hidden;
		position: relative;
	}

	.item-image {
		width: 690upx;
		height: 426upx;
	}
	.item-intro {
		width: 650upx;
		position: absolute;
		bottom: 0;
		padding: 20upx;
		background-color: rgba(0,0,0,0.3);
	}
	.item-intro-text {
		color: #FFFFFF;
		font-size: 30upx;
		
		//两行
		text-overflow: -o-ellipsis-lastline;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 3;
		line-clamp: 3;
		-webkit-box-orient: vertical;
	}
	.item-time {
		color: #FFFFFF;
		font-size: 30upx;
		position: absolute;
		top: 0;
		left: 0;
		padding: 10rpx 20upx;
		width: 100%;
		/* background-color: rgba(220,95,49,0.7); */
		background: linear-gradient(to right, rgba(220,40,7,0.8), rgba(220,40,7,0.2));
		/* border-bottom-left-radius: 20rpx; */
	}
	.item-mer-view {
		width: 650upx;
		height: 50upx;
		margin: 20upx 20upx 10upx;
	}
	.item-mer-name {
		height: 50upx;
		font-size: 36upx;
		line-height: 50upx;
		color: #333333;
		float: left;
	}
	.item-mer-distance {
		height: 50upx;
		font-size: 28upx;
		line-height: 50upx;
		color: #bbbbbb;
		float: right;
	}
	
	.price-view {
		width: 650upx;
		height: 55upx;
		margin: 10upx 20upx 20upx;
	}
	.price-icon {
		height: 55upx;
		line-height: 55upx;
		color: #d8622c;
		font-size: 28upx;
		float: left;
		position: relative;
		top: 8upx;
	}
	.price-text {
		height: 55upx;
		line-height: 55upx;
		color: #d8622c;
		font-size: 52upx;
		float: left;
	}
	.price-brokerage {
		padding: 3upx 10upx 3upx;
		background-color: #ec6e2d;
		float: right;
		height: 40upx;
		line-height: 40upx;
		border-radius: 6upx;
		color: #FFFFFF;
		font-size: 25upx;
		margin-top: 5upx;
	}
	.price-red-packet {
		padding: 5upx 10upx 5upx;
		float: left;
		height: 25upx;
		line-height: 25upx;
		border: 1upx solid #f8dedc;
		border-radius: 10upx;
		color: #ec6863;
		font-size: 18upx;
		margin-top: 15upx;
		margin-left: 20upx;
	}
	.price-original {
		padding: 5upx 10upx 5upx;
		float: left;
		height: 25upx;
		line-height: 25upx;
		color: #bbbbbb;
		font-size: 24upx;
		margin-top: 15upx;
		margin-left: 20upx;
	}

	/* 空数据提示 */
	.empty-view {
		text-align: center;
		margin-top: 200upx;
	}

	.empty-image {
		width: 300upx;
		height: 210upx;
	}

	.empty-title {
		color: #999999;
		font-size: 32upx;
		margin-top: 30upx;
	}
</style>
